package com.youlai.boot.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.model.Option;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.converter.SpotCategoryConverter;
import com.youlai.boot.system.enums.YesNoEnum;
import com.youlai.boot.system.mapper.SpotCategoryMapper;
import com.youlai.boot.system.model.entity.Dept;
import com.youlai.boot.system.model.entity.SpotCategory;
import com.youlai.boot.system.model.entity.SpotTravel;
import com.youlai.boot.system.model.form.SpotCategoryForm;
import com.youlai.boot.system.model.query.SpotCategoryQuery;
import com.youlai.boot.system.model.vo.SpotCategoryVO;
import com.youlai.boot.system.service.SpotCategoryService;
import com.youlai.boot.system.service.SpotTravelService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预售票分类服务实现类
 *
 * @author lwb
 * @since 2025-06-29 16:31
 */
@Service
@RequiredArgsConstructor
public class SpotCategoryServiceImpl extends ServiceImpl<SpotCategoryMapper, SpotCategory> implements SpotCategoryService {

    private final SpotCategoryConverter spotCategoryConverter;

    private final SpotTravelService spotTravelService;

    /**
     * 获取预售票分类分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<SpotCategoryVO>} 预售票分类分页列表
     */
    @Override
    public IPage<SpotCategoryVO> getSpotCategoryPage(SpotCategoryQuery queryParams) {
        Page<SpotCategoryVO> pageVO = this.baseMapper.getSpotCategoryPage(new Page<>(queryParams.getPageNum(), queryParams.getPageSize()), queryParams);
        return pageVO;
    }

    /**
     * 获取预售票分类表单数据
     *
     * @param id 预售票分类ID
     * @return
     */
    @Override
    public SpotCategoryForm getSpotCategoryFormData(Long id) {
        SpotCategory entity = this.getById(id);
        return spotCategoryConverter.toForm(entity);
    }

    /**
     * 新增预售票分类
     *
     * @param formData 预售票分类表单对象
     * @return
     */
    @Override
    public boolean saveSpotCategory(SpotCategoryForm formData) {
        long count = this.count(new LambdaQueryWrapper<SpotCategory>().eq(SpotCategory::getName, formData.getName()).eq(SpotCategory::getIsDeleted, YesNoEnum.NO.getType()));
        Assert.isTrue(count == 0, "预售票分类已存在！");
        SpotCategory entity = spotCategoryConverter.toEntity(formData);
        fieldFill(entity);
        return this.save(entity);
    }

    public void fieldFill(SpotCategory entity) {
        Long userId = SecurityUtils.getUserId();
        LocalDateTime now = LocalDateTime.now();
        if (entity.getId() == null) {
            entity.setCreateBy(userId);
            entity.setCreateTime(now);
            entity.setUpdateBy(userId);
            entity.setUpdateTime(now);
        } else {
            entity.setUpdateBy(userId);
            entity.setUpdateTime(now);
        }
    }

    /**
     * 更新预售票分类
     *
     * @param id       预售票分类ID
     * @param formData 预售票分类表单对象
     * @return
     */
    @Override
    public boolean updateSpotCategory(Long id, SpotCategoryForm formData) {
        long count = this.count(new LambdaQueryWrapper<SpotCategory>().eq(SpotCategory::getName, formData.getName()).eq(SpotCategory::getIsDeleted, YesNoEnum.NO.getType()).ne(SpotCategory::getId, id));
        Assert.isTrue(count == 0, "预售票分类已存在！");
        SpotCategory entity = spotCategoryConverter.toEntity(formData);
        fieldFill(entity);
        return this.updateById(entity);
    }

    /**
     * 删除预售票分类
     *
     * @param ids 预售票分类ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSpotCategorys(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的预售票分类数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();

        List<SpotTravel> spotTravelList = spotTravelService.getByCategorysId(idList);
        if (CollectionUtil.isNotEmpty(spotTravelList)) {
            List<Long> categorysIds = spotTravelList.stream().map(SpotTravel::getCategoryId).collect(Collectors.toList());
            List<SpotCategory> categoryList = baseMapper.selectBatchIds(categorysIds);
            if (CollUtil.isEmpty(categoryList)) {
                throw new BusinessException("预售票分类数据不存在！");
            }
            String names = categoryList.stream().map(SpotCategory::getName).collect(Collectors.joining(","));
            String mes = names + "存在余票无法删除该分类！";
            throw new BusinessException(mes);
        }
        return this.removeByIds(idList);
    }

    @Override
    public List<Option<Long>> listSpotCategorysOptions() {
        List<SpotCategory> deptList = baseMapper.listSpotCategorysOptions();
        if (CollectionUtil.isEmpty(deptList)) {
            return Collections.EMPTY_LIST;
        }
        return deptList.stream().map(dept -> new Option<>(dept.getId(), dept.getName())).toList();
    }

    /**
     * @param categoryId
     * @return
     */
    @Override
    public SpotCategory getCategoryById(Long categoryId) {
        return baseMapper.getCategoryById(categoryId);
    }
}
